package com.saxon.system.ajax;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 莫松
 */
@Component
public class UnauthorizedEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence (HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        if (isAjax (request)) {
            response.sendError (HttpServletResponse.SC_UNAUTHORIZED, authException.getMessage ());
        } else {
            response.sendRedirect ("/login");
        }
    }

    public static boolean isAjax (HttpServletRequest request) {
        //判断请求的头
        String flag = request.getHeader ("X-Requested-With");
        return "XMLHttpRequest".equals (flag);
    }
}
